package com.fa4j.common.base.util;

import com.fa4j.common.base.model.DiffList;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Function;

public class DiffListUtil {

    /**
     * 比较列表差异
     *
     * @param existList    已经存在的列表
     * @param overrideList 覆盖的列表
     * @param uniqueFun    唯一性方法
     * @param <T>          列表的对象类型
     * @return 差异列表结果
     */
    public static <T> DiffList<T> diff(List<T> existList, List<T> overrideList, Function<T, ?> uniqueFun, BiConsumer<T, T> consumer) {
        List<T> createList = new ArrayList<>();
        List<T> modifyList = new ArrayList<>();
        List<T> removeList = new ArrayList<>();

        for (T obj : overrideList) {
            T existObj = null;
            if (existList != null) {
                for (T exist : existList) {
                    if (Objects.equals(uniqueFun.apply(exist), uniqueFun.apply(obj))) {
                        existObj = exist;
                        break;
                    }
                }
            }

            if (existObj == null) {
                consumer.accept(null, obj);
                createList.add(obj);
            } else {
                consumer.accept(existObj, obj);
                modifyList.add(obj);
            }
        }
        if (existList != null) {
            for (T exist : existList) {
                T modifyObj = null;
                for (T modify : modifyList) {
                    if (Objects.equals(uniqueFun.apply(exist), uniqueFun.apply(modify))) {
                        modifyObj = modify;
                    }
                }
                if (modifyObj == null) {
                    consumer.accept(null, exist);
                    removeList.add(exist);
                }
            }
        }
        return new DiffList<>(createList, modifyList, removeList);
    }
}
